package com.googlecode.imanager.client.io;

import java.io.Serializable;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class Path implements Serializable, Cloneable {
    
    private static final long serialVersionUID = 1L;

    private static final String PATH_SEPARATOR = "/";

    private final String value;
    
    public Path(String value) {
        this(null, value);
    }
    
    public Path(Path contextPath, String subPath) {
        this.value = buildPathString(contextPath, subPath);
    }

    public String getValue() {
        return value;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj instanceof Path){
            return getValue().equals(((Path) obj).getValue());
        }
        return false;
    }

    @Override
    public String toString() {
        return getValue();
    }
        
    private static String buildPathString(Path path, String val) {                
        if (path == null){
            if (val == null){
                return "";
            }
            return val;
        }
        
        String addr = path.toString();

        if (val == null
                || val.length() == 0){
            return addr;
        }
        
        if (addr.length() == 0){
            return val;
        }

        if (addr.endsWith(PATH_SEPARATOR)){
            if (val.startsWith(PATH_SEPARATOR)){
                return addr + val.substring(1);
            } else {
                return addr + val;
            }
        } else {
            if (val.startsWith(PATH_SEPARATOR)){
                return addr + val;
            } else {
                return addr + PATH_SEPARATOR + val;
            }
        }
    }
    
    @Override
    public int hashCode() {
        return getValue().hashCode();
    }

    @Override
    public Path clone() {
        try {
            return (Path) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getPathSeparator(){
        return PATH_SEPARATOR;
    }
    
}
